/*
 * @Author: ZhanXie
 * @Date: 2020-08-11 10:13:00
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-09-16 22:39:22
 * @Description: 
 * @FilePath: /weibo/src/app.js
 */
const path = require('path')
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const koaStatic = require('koa-static')
// const jwtKoa = require('koa-jwt')

const userApiRouter = require('./routes/api/user')
const blogHomeApiRouter = require('./routes/api/blog-home')
const blogSquareApiRouter = require('./routes/api/blog-square')
const blogProfileApiRouter = require('./routes/api/blog-profile')
const utilsApiRouter = require('./routes/api/utils')
const blogAtApiRouter = require('./routes/api/blog-at')

const blogViewRouter = require('./routes/view/blog')
const userViewRouter = require('./routes/view/user')
const errorViewRouter = require('./routes/view/error')

const { isProd } = require('./utils/env')
const { CRYPTO_SECRET_KEY } = require('./conf/secretKeys')
const { MYSQL_CONF } = require('./conf/db')

// error handler
let onerrorConf = {}
if (isProd) {
  onerrorConf = {
    redirect: '/error'
  }
}
onerror(app, onerrorConf)

// jwt统一校验token
// app.use(jwtKoa({
//   secret: SECRET // 密钥
// }).unless({
//   path: [/^\/api\/user\/login/, /^\/api\/user\/register/] // 登录和注册不需要jwt验证
// }))

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(koaStatic(__dirname + '/public'))
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')))

app.use(views(__dirname + '/views', {
  extension: 'pug',
  extension: 'ejs',
}))

// session 配置
app.keys = [CRYPTO_SECRET_KEY]
app.use(session({
  key: 'weibo.sid', // cookie name 默认 koa.sid,
  prefix: 'weibo:sess:', // redis key 的前缀 默认 koa:sess:
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 24 * 60 * 1000 * 7 // 过期时间 ms 1个星期
  },
  // ttl: 24 * 60 * 1000, // redis 过期时间
  store: redisStore({
    all: `${MYSQL_CONF.host}:${MYSQL_CONF.port}`
  }), // 把 session 存在 redis 中
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(userApiRouter.routes(), userApiRouter.allowedMethods())
app.use(blogHomeApiRouter.routes(), blogHomeApiRouter.allowedMethods())
app.use(blogProfileApiRouter.routes(), blogProfileApiRouter.allowedMethods())
app.use(blogSquareApiRouter.routes(), blogSquareApiRouter.allowedMethods())
app.use(blogAtApiRouter.routes(), blogAtApiRouter.allowedMethods())
app.use(utilsApiRouter.routes(), utilsApiRouter.allowedMethods())

app.use(blogViewRouter.routes(), blogViewRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods())
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods()) // 404 注册路由

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
